//
//  CLStoreManager.m
//  qiyuerciyuan
//
//  Created by culiu-macBook Air on 2018/6/20.
//  Copyright © 2018年 culiu-macBook Air. All rights reserved.
//

#import "CLStoreManager.h"
#import <StoreKit/StoreKit.h>

@interface CLStoreManager () <SKProductsRequestDelegate,SKPaymentTransactionObserver>

@property (nonatomic,copy) NSString *productId;

@end
@implementation CLStoreManager

+ (instancetype)defaultManager {
    static CLStoreManager *_defaultManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _defaultManager = [[self alloc] init];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:_defaultManager];
    });
    return _defaultManager;
}
- (void)startPayWithProductId:(NSString *)productId success:(void (^)(id responseObject))successBlock failed:(void (^)(id responseObject))failedBlock {
    self.productId = productId;
    _successBlock = successBlock;
    _failedBlock = failedBlock;
    if ([SKPaymentQueue canMakePayments]){
        [self requestProductData:self.productId];
    }
}
- (void)requestProductData:(NSString *)productId {
    NSSet *nsset = [NSSet setWithObjects:productId, nil];
    SKProductsRequest * _request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    _request.delegate = self;
    [_request start];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray *products = response.products;
    if (products.count == 0) {
        //没有商品
        if (_failedBlock) {
            _failedBlock(nil);
        }
        return;
    }
    SKProduct *prod = nil;
    for (SKProduct *pro in products) {
        if ([pro.productIdentifier isEqualToString:self.productId]) {
            prod = pro;
        }
    }
    if (prod != nil) {
        SKPayment *payment = [SKPayment paymentWithProduct:prod];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }else{
        if (_failedBlock) {
            _failedBlock(nil);
        }
    }
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    //请求失败
    if (_failedBlock) {
        _failedBlock(error);
    }
}

- (void)requestDidFinish:(SKRequest *)request {
    //反馈信息结束
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *tran in transactions) {
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
            {
                //成功
                [self completeTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:
            {
                //商品添加进列表
            }
                break;
            case SKPaymentTransactionStateRestored:
            {
                //已经购买过
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
             }
                break;
            case SKPaymentTransactionStateFailed:
            {
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                if (_failedBlock) {
                    _failedBlock(nil);
                }
            }
                break;
            default:
                break;
        }
    }
}

//沙盒测试环境验证
#define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"
//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
//    [[CLNNNativeServer sharedInstance] requestInAppPurchaseWithReceipt:receiptString withpackageId:self.productId Success:^(id responseObject) {
    
    //没有校验
        if (_successBlock) {
            _successBlock(nil);
        }
//    } failure:^(CLRequestErrorModel *model) {
//        if (_failedBlock) {
//            _failedBlock(nil);
//        }
//    }];
    
    
        
//
//        NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
//        NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//        NSURL *url=[NSURL URLWithString:SANDBOX];
//        NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
//        requestM.HTTPBody=bodyData;
//        requestM.HTTPMethod=@"POST";
//        [[[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//            if (error) {
//                NSLog(@"验证购买过程中发生错误，错误信息：%@",error.localizedDescription);
//                return;
//            }
//            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//            NSLog(@"%@",data);
//            if([dic[@"status"] intValue]==0){
//                NSDictionary *dicReceipt= dic[@"receipt"];
//
//                NSString *receiptString = [dicReceipt jsonStringEncoded];
//                NSData *data = [receiptString dataUsingEncoding:NSUTF8StringEncoding];
//                NSString *base64String = [data base64EncodedStringWithOptions:0];
//
//
//                [[CLNNNativeServer sharedInstance] requestInAppPurchaseWithReceipt:base64String withpackageId:self.productId Success:^(id responseObject) {
//                            if (_successBlock) {
//                                _successBlock(nil);
//                            }
//                        } failure:^(CLRequestErrorModel *model) {
//                            if (_failedBlock) {
//                                _failedBlock(nil);
//                            }
//                    }];
//            }else{
//                NSLog(@"购买失败，未通过验证！");
//            }
//        }] resume];
}


@end
